package com.wfcm.controller;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.wfcm.annotation.IgnoreSign;
import com.wfcm.annotation.IgnoreToken;
import com.wfcm.utils.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.util.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wfcm.entity.WfCourseCommentEntity;
import com.wfcm.entity.WfMemberEntity;
import com.wfcm.service.WfCourseCommentService;
import com.wfcm.service.WfMemberService;
import org.springframework.web.multipart.MultipartFile;


/**
 * 评论点赞
 */
@Controller
@RequestMapping("/courseOperation")
@ResponseBody
public class CourseOperationController {

	private Logger log = LoggerFactory.getLogger(AdInfoController.class);
	@Autowired
	WfCourseCommentService courseCommentService;
	@Autowired
	WfMemberService memberService;
	
	/**
	 * 评论点赞(1.点赞 2.评论)
	 */
	@RequestMapping("/add")
	@ResponseBody
	public R addCourseOperation(HttpServletRequest req, WfCourseCommentEntity entity, MultipartFile file) {
		//获取前台传来的数据
		Integer userid =  ISsoLoginHelper.confirm(req);
		WfCourseCommentEntity wfCourseComment = new WfCourseCommentEntity();
		Integer chapterid = entity.getChapterid();
		Integer commenttype = entity.getCommenttype();
		wfCourseComment.setUserid(userid);
		wfCourseComment.setChapterid(chapterid);
		wfCourseComment.setCommenttype(commenttype);
		wfCourseComment.setCommenttime(new Date());
		String commentcontent = null;
		// 黑名单用户评论不保存
		if (memberService.queryObject(userid).getBlackflag().equals(1)) {
			log.error("黑名单用户ID：" + userid + "，评论内容为：" + entity.getCommentcontent() + "。");
			return R.ok();
		}
		//当评论时，获取评论内容
		if(commenttype == 2){
			commentcontent = entity.getCommentcontent();
			wfCourseComment.setCommentcontent(commentcontent);
		}
		System.err.println("commentcontent: " + commentcontent);
		
		Map<String,Object>  map = new HashMap<String,Object>();
		map.put("userid", userid);
		WfMemberEntity member = memberService.queryObject(userid);
		wfCourseComment.setNickname(member.getUsername());
		wfCourseComment.setHeadimage(member.getHeadimage());
		
		map.put("chapterid", chapterid);
		map.put("commenttype", commenttype);
		//点赞校验
		if(commenttype == 1){
			List<WfCourseCommentEntity> courseCommentList =  courseCommentService.queryList(map);
			if( courseCommentList.size() >= 1) {
				return R.error(53,"您已经点赞过了!");
			}
		}else if(commenttype == 2) {
			map.put("commentcontent", commentcontent);
			List<WfCourseCommentEntity> courseCommentList =  courseCommentService.queryList(map);
			if( courseCommentList.size() >= 1) {
				return R.error(54,"您不能重复同样内容的评论!");
			}
			map.remove("commentcontent");
			System.out.println("#############时间：######"+new Date().toString()+"#########################");
			List<WfCourseCommentEntity> courseCommentLists =  courseCommentService.queryList(map);
			if(courseCommentLists != null  && courseCommentLists.size() >= 2 ) {
				return R.error(55,"评论失败，每节课程最多评论二次!");
			}
		} 
		String commentImage = null;
		if (null != file && !file.isEmpty()) {
			try {
				commentImage = OSSUtil.addFile(file, "comment", Constants.IGM_BUCKET);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		if (StringUtils.isNotBlank(entity.getCommentImage())) {
			try {
				byte[] buffer = new Base64().decode(entity.getCommentImage());
				InputStream is = new ByteArrayInputStream(buffer);
				commentImage = OSSUtil.putFile(is, "comment", Constants.IGM_BUCKET);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage(), e);
			}
		}
		if (null != commentImage) wfCourseComment.setCommentImage(commentImage);
		courseCommentService.save(wfCourseComment);
		return R.ok();
		
	}

	/**
	 * 上传评论图片
	 */
	@RequestMapping("/addCommentImage")
	@ResponseBody
	@IgnoreToken
	@IgnoreSign
	public R addCourseOperation(MultipartFile file) {
		String commentImage = null;
		if (null != file && !file.isEmpty()) {
			try {
				commentImage = OSSUtil.addFile(file, "comment", Constants.IGM_BUCKET);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		return R.ok().put("commentImage",commentImage);
	}

	/**
	 * 评论点赞(1.点赞 2.评论)
	 */
	@RequestMapping("/H5add")
	@ResponseBody
	public R addCourseOperationH5(HttpServletRequest req, WfCourseCommentEntity entity, MultipartFile file) {
		//获取前台传来的数据
		Integer userid =  ISsoLoginHelper.confirm(req);
		WfCourseCommentEntity wfCourseComment = new WfCourseCommentEntity();
		Integer chapterid = entity.getChapterid();
		Integer commenttype = entity.getCommenttype();
		wfCourseComment.setUserid(userid);
		wfCourseComment.setChapterid(chapterid);
		wfCourseComment.setCommenttype(commenttype);
		wfCourseComment.setCommenttime(new Date());
		// 黑名单用户评论不保存
		if (memberService.queryObject(userid).getBlackflag().equals(1)) {
			log.error("黑名单用户ID：" + userid + "，评论内容为：" + entity.getCommentcontent() + "。");
			return R.ok();
		}
		//当评论时，获取评论内容
		if(commenttype == 2){
			String keywords = null;
			wfCourseComment.setCommentcontent(entity.getCommentcontent());
		}
		log.debug("wfCourseComment:"+wfCourseComment.toString());
		
		Map<String,Object>  map = new HashMap<String,Object>();
		map.put("userid", userid);
		WfMemberEntity member = memberService.queryObject(userid);
		wfCourseComment.setNickname(member.getUsername());
		wfCourseComment.setHeadimage(member.getHeadimage());
		
		map.put("chapterid", chapterid);
		map.put("commenttype", commenttype);
		//点赞校验
		if(commenttype == 1){
			List<WfCourseCommentEntity> courseCommentList =  courseCommentService.queryList(map);
			if( courseCommentList.size() >= 1) {
				return R.error(53,"您已经点赞过了!");
			}
		}else if(commenttype == 2) {
			map.put("commentcontent", entity.getCommentcontent());
			List<WfCourseCommentEntity> courseCommentList =  courseCommentService.queryList(map);
			if( courseCommentList.size() >= 1) {
				return R.error(54,"您不能重复同样内容的评论!");
			}
			map.remove("commentcontent");
			System.out.println("#############时间：######"+new Date().toString()+"#########################");
			List<WfCourseCommentEntity> courseCommentLists =  courseCommentService.queryList(map);
			if(courseCommentLists != null  && courseCommentLists.size() >= 2 ) {
				return R.error(55,"评论失败，每节课程最多评论二次!");
			}
		}
		String commentImage = null;
		if (null != file && !file.isEmpty()) {
			try {
				commentImage = OSSUtil.addFile(file, "comment", Constants.IGM_BUCKET);
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			}
		}
		if (null != commentImage) wfCourseComment.setCommentImage(commentImage);
		courseCommentService.save(wfCourseComment);
		return R.ok();
	}
	
	/**
	 * 删除评论
	 */
	@RequestMapping("/del")
	@ResponseBody
	public R delOperation(HttpServletRequest req) {
		//获取前台传来的数据
		Integer chapterid = Integer.valueOf(req.getParameter("commentid"));
		WfCourseCommentEntity entity = courseCommentService.queryObject(chapterid);
		if (null != entity && StringUtils.isNotBlank(entity.getCommentImage())) {
			OSSUtil.delete(entity.getCommentImage(), Constants.IGM_BUCKET);
		}
		courseCommentService.delete(chapterid);
		return R.ok();
		
	}
	
	/**
     * 检测是否有emoji字符
     * @param source
     * @return 一旦含有就抛出
     */
    public static boolean containsEmoji(String source) {
        if (StringUtils.isBlank(source)) {
            return false;
        }

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                //do nothing，判断到了这里表明，确认有表情字符
                return true;
            }
        }

        return false;
    }

    private static boolean isEmojiCharacter(char codePoint) {
        return (codePoint == 0x0) ||
                (codePoint == 0x9) ||
                (codePoint == 0xA) ||
                (codePoint == 0xD) ||
                ((codePoint >= 0x20) && (codePoint <= 0xD7FF)) ||
                ((codePoint >= 0xE000) && (codePoint <= 0xFFFD)) ||
                ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF));
    }

    /**
     * 过滤emoji 或者 其他非文字类型的字符
     * @param source
     * @return
     */
    public static String filterEmoji(String source) {

        if (!containsEmoji(source)) {
            return source;//如果不包含，直接返回
        }
        //到这里铁定包含
        StringBuilder buf = null;

        int len = source.length();

        for (int i = 0; i < len; i++) {
            char codePoint = source.charAt(i);

            if (isEmojiCharacter(codePoint)) {
                if (buf == null) {
                    buf = new StringBuilder(source.length());
                }

                buf.append(codePoint);
            } else {
            }
        }

        if (buf == null) {
            return source;//如果没有找到 emoji表情，则返回源字符串
        } else {
            if (buf.length() == len) {//这里的意义在于尽可能少的toString，因为会重新生成字符串
                buf = null;
                return source;
            } else {
                return buf.toString();
            }
        }

    }
}
